package cn.webank.framework.gns.integration.support;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import cn.webank.gns.DCNInfo;
import cn.webank.gns.GNSException;
import cn.webank.gns.protobuf.GNS_INPUT_TYPE;
import cn.webank.gns.protobuf.GnsMsg;
import cn.webank.gns.protobuf.GnsMsg.BatchQueryDcnReq;
import cn.webank.gns.protobuf.GnsMsg.BatchQueryDcnRsp;
import cn.webank.gns.protobuf.GnsMsg.GetAllDcnReq;
import cn.webank.gns.protobuf.GnsMsg.GetAllDcnRsp;
import cn.webank.gns.protobuf.GnsMsg.QueryInput;
import cn.webank.gns.protobuf.GnsMsg.QueryOutput;
import cn.webank.gns.util.Constants;
import cn.webank.rmb.api.Response;
import cn.webank.rmb.common.ConfigUtil;

@Repository("cn.webank.framework.gns.integration.support.GNSWrapper")
public class GNSWrapper {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(GNSWrapper.class);
	private static final String DMZ_POSTFIX = "D0";
	private static final String ECN_POSTFIX = "E0";
	private Properties prop;

	public GNSWrapper() {

	}

	public GNSWrapper(Properties prop) {
		this.prop = prop;

	}

	public void setProrperties(Properties prop) {
		this.prop = prop;
	}

	public String getCcifDcn() {
		Assert.notNull(this.prop, "properties is null");
		return this.prop.getProperty("gns.client.ccifdcn");
	}

	public String getCSDcn() {
		Assert.notNull(this.prop, "properties is null");
		return this.prop.getProperty("gns.client.csdcn");
	}

	/**
	 * 通过银行卡号查询DCN
	 * 
	 * @param bankCardNo
	 *            银行卡号
	 * @return dcn号
	 * @throws GNSException
	 *             gns异常
	 */
	public String queryByBankCardNo(String bankCardNo) throws GNSException {
		LOGGER.debug("enter queryByBankCardNo() param:" + bankCardNo);
		long begin = System.currentTimeMillis();
		if (bankCardNo == null) {
			return null;
		}
		List<String> reqList = Arrays.asList(bankCardNo);
		byte[] bytes = queryInput(reqList, Constants.QUERYBYBANKCARDNO);
		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		String dcnNumber = null;
		try {
			dcnNumber = getReponseDcn(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByBankCardNo() result:" + dcnNumber + ",cost:"
				+ (end - begin));
		return dcnNumber;
	}

	/**
	 * 通过微信账号查询DCN
	 * 
	 * @param wechatAccount
	 *            微信账号
	 * @return dcn号
	 * @throws GNSException
	 *             gns异常
	 */
	public String queryByWechatAccount(String wechatAccount)
			throws GNSException {
		LOGGER.debug("enter queryByWechatAccount() param:" + wechatAccount);
		long begin = System.currentTimeMillis();
		if (wechatAccount == null) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(wechatAccount),
				Constants.QUERYBYWECHATACCOUNT);

		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		String dcnNumber = null;
		try {
			dcnNumber = getReponseDcn(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByBankCardNo() result:" + dcnNumber + ",cost:"
				+ (end - begin));
		return dcnNumber;

	}

	/**
	 * 通过qq号查询DCN
	 * 
	 * @param qqNo
	 *            qq号
	 * @return dcn号
	 * @throws GNSException
	 *             gns异常
	 */
	public String queryByQQNo(String qqNo) throws GNSException {
		LOGGER.debug("enter queryByQQNo() param:" + qqNo);
		long begin = System.currentTimeMillis();
		if (qqNo == null) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(qqNo), Constants.QUERYBYQQNO);
		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		String dcnNumber = null;
		try {
			dcnNumber = getReponseDcn(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByQQNo() result:" + dcnNumber + ",cost:"
				+ (end - begin));
		return dcnNumber;
	}

	/**
	 * 通过用户ID查询DCN
	 * 
	 * @param userID
	 *            用户ID
	 * @return DCN
	 * @throws GNSException
	 *             gns异常
	 */
	public String queryByUserID(String userID) throws GNSException {
		LOGGER.debug("enter queryByUserID() param:" + userID);
		long begin = System.currentTimeMillis();
		if (userID == null) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(userID),
				"queryByUserID(String userID)");

		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		String dcnNumber = null;
		try {
			dcnNumber = getReponseDcn(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByUserID() result:" + dcnNumber + ",cost:"
				+ (end - begin));
		return dcnNumber;
	}

	/**
	 * 通过银行账号查询DCN
	 * 
	 * @param bankAccount
	 *            银行账号
	 * @return DCN DCN号
	 * @throws GNSException
	 *             gns异常
	 */
	public String queryByBankAccount(String bankAccount) throws GNSException {
		LOGGER.debug("enter queryByBankAccount() param:" + bankAccount);
		long begin = System.currentTimeMillis();
		if (bankAccount == null) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(bankAccount),
				Constants.QUERYBYBANKACCOUNT);
		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		String dcnNumber = null;
		try {
			dcnNumber = getReponseDcn(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByBankAccount() result:" + dcnNumber + ",cost:"
				+ (end - begin));
		return dcnNumber;
	}

	/**
	 * 通过ecif号查询DCN
	 * 
	 * @param ecifNo
	 *            ecif号
	 * @return DCN
	 * @throws GNSException
	 *             gns异常
	 */
	public String queryByEcifNo(String ecifNo) throws GNSException {
		LOGGER.debug("enter queryByEcifNo() param:" + ecifNo);
		long begin = System.currentTimeMillis();
		if (ecifNo == null) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(ecifNo),
				Constants.QUERYBYECIFNO);

		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		String dcnNumber = null;
		try {
			dcnNumber = getReponseDcn(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.info("exit queryByBankAccount() result:" + dcnNumber + ",cost:"
				+ (end - begin));
		return dcnNumber;
	}

	/**
	 * 根据电话号码查询DCN
	 * 
	 * @param moblie
	 *            电话号码
	 * @return dcn号
	 * @throws GNSException
	 *             gns异常
	 */
	public String queryByMoblie(String moblie) throws GNSException {
		LOGGER.debug("enter queryByMoblie() param:" + moblie);
		long begin = System.currentTimeMillis();
		if (moblie == null) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(moblie),
				Constants.QUERYBYMOBLIE);

		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		String dcnNumber = null;
		try {
			dcnNumber = getReponseDcn(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByMoblie() result:" + dcnNumber + ",cost:"
				+ (end - begin));
		return dcnNumber;
	}

	/**
	 * 根据openId查询DCN
	 * 
	 * @param openId
	 *            openId
	 * @return dcnNo
	 * @throws GNSException
	 *             gns异常
	 */
	public String queryByOpenId(String openId) throws GNSException {
		LOGGER.debug("enter queryByOpenId() param:" + openId);
		long begin = System.currentTimeMillis();
		if (openId == null) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(openId),
				Constants.QUERYBYOPENID);

		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		String dcnNumber = null;
		try {
			dcnNumber = getReponseDcn(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByOpenId() result:" + dcnNumber + ",cost:"
				+ (end - begin));
		return dcnNumber;
	}

	/**
	 * 批量查询，通过银行卡号查询DCN
	 * 
	 * @param bankCardNo
	 *            银行卡号数组
	 * @return key为银行卡号,value为DCN的Map
	 * @throws GNSException
	 *             gns异常
	 */
	public Map<String, String> queryByBankCardNo(String[] bankCardNo)
			throws GNSException {
		LOGGER.debug("enter queryByBankCardNo() param:" + bankCardNo);
		long begin = System.currentTimeMillis();
		if (bankCardNo == null || bankCardNo.length <= 0) {
			return null;
		}

		byte[] bytes = queryInput(Arrays.asList(bankCardNo),
				Constants.QUERYBYBANKCARDNOS);
		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		Map<String, String> dcnNumberMap = null;
		try {
			dcnNumberMap = getResponseDcnList(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByBankCardNo() result:" + dcnNumberMap
				+ (end - begin));
		return dcnNumberMap;
	}

	/**
	 * 批量查询，通过qq号查询DCN
	 * 
	 * @param qqNo
	 *            qq号数组
	 * @return key为qq号,value为DCN的Map
	 * @throws GNSException
	 *             gns异常
	 */
	public Map<String, String> queryByQQNo(String[] qqNo) throws GNSException {
		LOGGER.debug("enter queryByQQNo() param:" + qqNo);
		long begin = System.currentTimeMillis();
		if (qqNo == null || qqNo.length <= 0) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(qqNo), Constants.QUERYBYQQNOS);
		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		Map<String, String> dcnNumberMap = null;
		try {
			dcnNumberMap = getResponseDcnList(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByQQNo() result:" + dcnNumberMap
				+ (end - begin));
		return dcnNumberMap;
	}

	/**
	 * 批量查询，通过微信账号查询DCN
	 * 
	 * @param wechatAccount
	 *            微信账号数组
	 * @return key为微信账号,value为DCN的Map
	 * @throws GNSException
	 *             gns异常
	 */
	public Map<String, String> queryByWechatAccount(String[] wechatAccount)
			throws GNSException {
		LOGGER.debug("enter queryByWechatAccount() param:" + wechatAccount);
		long begin = System.currentTimeMillis();
		if (wechatAccount == null || wechatAccount.length <= 0) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(wechatAccount),
				Constants.QUERYBYWECHATACCOUNTS);

		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		Map<String, String> dcnNumberMap = null;
		try {
			dcnNumberMap = getResponseDcnList(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByWechatAccount() result:" + dcnNumberMap
				+ ",cost:" + (end - begin));
		return dcnNumberMap;
	}

	/**
	 * 批量查询，通过银行账号查询DCN
	 * 
	 * @param bankAccount
	 *            银行账号数组
	 * @return key为银行账号,value为DCN的Map
	 * @throws GNSException
	 *             gns异常
	 */
	public Map<String, String> queryByBankAccount(String[] bankAccount)
			throws GNSException {
		long begin = System.currentTimeMillis();
		LOGGER.debug("enter queryByBankAccount() param:" + bankAccount);
		if (bankAccount == null || bankAccount.length <= 0) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(bankAccount),
				Constants.QUERYBYBANKACCOUNTS);

		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		Map<String, String> dcnNumberMap = null;
		try {
			dcnNumberMap = getResponseDcnList(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByBankAccount() result:" + dcnNumberMap
				+ ",cost:" + (end - begin));
		return dcnNumberMap;
	}

	/**
	 * 批量查询，通过Ecif号查询DCN
	 * 
	 * @param ecifNo
	 *            Ecif号数组
	 * @return key为Ecif号,value为DCN的Map
	 * @throws GNSException
	 *             gns异常
	 */
	public Map<String, String> queryByEcifNo(String[] ecifNo)
			throws GNSException {
		LOGGER.debug("enter queryByEcifNo() param:" + ecifNo);
		long begin = System.currentTimeMillis();
		if (ecifNo == null || ecifNo.length <= 0) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(ecifNo),
				Constants.QUERYBYECIFNOS);
		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		Map<String, String> dcnNumberMap = null;
		try {
			dcnNumberMap = getResponseDcnList(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByBankAccount() result:" + dcnNumberMap
				+ (end - begin));
		return dcnNumberMap;
	}

	/**
	 * 根据电话号码批量查询
	 * 
	 * @param mobiles
	 *            电话列表
	 * @return dcn map
	 * @throws GNSException
	 *             gns异常
	 */
	public Map<String, String> queryByMoblie(String[] mobiles)
			throws GNSException {
		LOGGER.debug("enter queryByMoblie() param:" + mobiles);
		long begin = System.currentTimeMillis();
		if (mobiles == null || mobiles.length <= 0) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(mobiles),
				Constants.QUERYBYMOBLIES);

		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		Map<String, String> dcnNumberMap = null;
		try {
			dcnNumberMap = getResponseDcnList(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.debug("exit queryByMoblie() result:" + dcnNumberMap + ",cost:"
				+ (end - begin));
		return dcnNumberMap;
	}

	/**
	 * 根据电话号码批量查询
	 * 
	 * @param openIds
	 *            openid列表
	 * @return dcn map
	 * @throws GNSException
	 *             gns异常
	 */
	public Map<String, String> queryByOpenId(String[] openIds)
			throws GNSException {
		LOGGER.info("enter queryByOpenId() param:" + openIds);
		long begin = System.currentTimeMillis();
		if (openIds == null || openIds.length <= 0) {
			return null;
		}
		byte[] bytes = queryInput(Arrays.asList(openIds),
				Constants.QUERYBYOPENIDS);

		Response response = GNSRMBRequestorWrapper.send(bytes, this.getCSDcn());
		Map<String, String> dcnNumberMap = null;
		try {
			dcnNumberMap = getResponseDcnList(response);
		} catch (InvalidProtocolBufferException e) {
			LOGGER.error(e.getMessage(), e);
		}
		long end = System.currentTimeMillis();
		LOGGER.info("exit queryByOpenId() result:" + dcnNumberMap + ",cost:"
				+ (end - begin));
		return dcnNumberMap;
	}

	/**
	 * 获取ADM所在的DCN
	 * 
	 * @return DCN号
	 * @throws GNSException
	 *             gns异常
	 */
	public String getAdminDCN() throws GNSException {
		LOGGER.debug("enter getAdminDCN() param:");
		long begin = System.currentTimeMillis();
		// GetAdminDcnReq.Builder builder = GetAdminDcnReq.newBuilder();
		// builder.setReqId(0);
		// GetAdminDcnReq adminDcnReq = builder.build();
		// byte[] bytes = adminDcnReq.toByteArray();
		// int subcmd = GnsMsg.SUBCMD_FOR_GNS.SUBCMD_GET_ADMIN_DCN_VALUE;
		// byte byteVal = Integer.valueOf(subcmd).byteValue();
		// byte[] sendBytes = mergeBytes(byteVal, bytes);
		//
		// Response response = GNSRMBRequestorWrapper.send(sendBytes);
		String result = ConfigUtil.getStringByKey("gns.client.admdcn",
				"gns-client.properties");
		// if (checkReponse(response)) {
		// String content = response.getMessage().getContent();
		// content = content.substring(1, content.length());
		// try {
		// GetAdminDcnRsp adminDcnRsp =
		// GetAdminDcnRsp.parseFrom(content.getBytes());
		// if (adminDcnRsp != null) {
		// List<ByteString> list = adminDcnRsp.getDcnListList();
		// if (list != null && !list.isEmpty()) {
		// if (list.get(0) != null) {
		// result = list.get(0).toStringUtf8();
		// }
		// }
		// }
		// } catch (InvalidProtocolBufferException e) {
		// LOGGER.error(e.getMessage(),e);
		// }
		// }
		long end = System.currentTimeMillis();
		LOGGER.debug("exit getAdminDCN() result:" + result + ",cost:"
				+ (end - begin));
		return result;
	}

	/**
	 * 获取ECN
	 * 
	 * @param dcn
	 *            dcn号
	 * @return ECN No
	 */
	public String getECN(String dcn) {

		// String ecn = csdcn.substring(0, 1) + ECN_POSTFIX;
		String ecn = this.getCSDcn().substring(0, 1) + ECN_POSTFIX;
		LOGGER.debug("exit getECN() result:" + ecn);
		return ecn;
	}

	/**
	 * 获取DMZ
	 * 
	 * @param dcn
	 *            用户所在dcn号
	 * @return DMZ
	 */
	public String getDMZ(String dcn) {
		String dmz = this.getCSDcn().substring(0, 1) + DMZ_POSTFIX;
		LOGGER.debug("exit getDMZ() result:" + dmz);
		return dmz;
	}

	/**
	 * 获取所有的dcn
	 * 
	 * @return 获取所有的dcn
	 * @throws GNSException
	 *             gns异常
	 */
	public List<DCNInfo> getAllDCN() throws GNSException {
		LOGGER.debug("enter getAllDCN() param:");
		GetAllDcnReq.Builder builder = GetAllDcnReq.newBuilder();
		builder.setReqId(0);
		GetAllDcnReq getAllDcnReq = builder.build();

		byte[] bytes = getAllDcnReq.toByteArray();
		int subcmd = GnsMsg.SUBCMD_FOR_GNS.SUBCMD_GET_ALL_DCN_VALUE;
		byte byteVal = Integer.valueOf(subcmd).byteValue();
		byte[] sendBytes = mergeBytes(byteVal, bytes);

		Response response = GNSRMBRequestorWrapper.send(sendBytes,
				this.getCSDcn());
		if (checkReponse(response)) {
			String content = response.getMessage().getContent();
			content = content.substring(1, content.length());
			try {
				GetAllDcnRsp getAllDcnRsp = GetAllDcnRsp.parseFrom(content
						.getBytes());
				List<ByteString> list = getAllDcnRsp.getDcnListList();
				if (list != null) {
					List<DCNInfo> dcnInfos = new ArrayList<DCNInfo>();
					for (ByteString byteString : list) {
						if (byteString != null) {
							String str = byteString.toStringUtf8();
							DCNInfo dcnInfo = new DCNInfo();
							dcnInfo.setIdc("001");
							dcnInfo.setDcn(str);
							dcnInfos.add(dcnInfo);
						}
					}
					return dcnInfos;
				}

			} catch (InvalidProtocolBufferException e) {
				LOGGER.error(e.getMessage(), e);
			}
		}

		LOGGER.debug("exit getAllDCN() result:");
		return null;
	}

	// /**
	// * 获取Ccif CDCN
	// *
	// * @param 组织机构号
	// * @return CDCN
	// */
	// public String queryCDCNByOrgNo(String orgNo) {
	// LOGGER.debug("enter queryCDCNByOrgNo() param:" + orgNo);
	// return cdcn;
	// }

	// /**
	// * 获取Ccif CDCN
	// *
	// * @param 营业执照号
	// * @return CDCN
	// */
	// public String queryCDCNByBizPermNo(String bizPermNo) {
	// LOGGER.debug("enter queryCDCNByBizPermNo() param:" + bizPermNo);
	// return cdcn;
	// }

	// /**
	// * 获取Ccif CDCN
	// *
	// * @param 金融许可证号
	// * @return CDCN
	// */
	// public String queryCDCNByFinLicNo(String finLicNo) {
	// LOGGER.debug("enter queryCDCNByFinLicNo() param:" + finLicNo);
	// return cdcn;
	// }

	// /**
	// * 获取Ccif CDCN
	// *
	// * @param 企业代码证号
	// * @return CDCN
	// */
	// public String queryCDCNByEntCode(String entCode) {
	// LOGGER.debug("enter queryCDCNByEntCode() param:" + entCode);
	// return cdcn;
	// }

	// /**
	// * 获取Ccif CDCN
	// *
	// * @param SWIFTCODE
	// * @return CDCN
	// */
	// public String queryCDCNBySwiftCode(String swiftCode) {
	// LOGGER.debug("enter queryCDCNBySwiftCode() param:" + swiftCode);
	// return cdcn;
	// }

	// /**
	// * 获取Ccif CDCN
	// *
	// * @param 兴业客户号
	// * @return CDCN
	// */
	// public String queryCDCNByXYClientNo(String clientNo) {
	// LOGGER.debug("enter queryCDCNByXYClientNo() param:" + clientNo);
	// return cdcn;
	// }

	// /**
	// * 获取Ccif CDCN
	// *
	// * @param qq号
	// * @return CDCN
	// */
	// public String queryCDCNByQQNo(String qqNo) {
	// LOGGER.debug("enter queryCDCNByQQNo() param:" + qqNo);
	// return cdcn;
	// }

	/**
	 * @return the prop
	 */
	public Properties getProp() {
		return prop;
	}

	/**
	 * @param prop
	 *            the prop to set
	 */
	public void setProp(Properties prop) {
		this.prop = prop;
	}

	// /**
	// * 获取Ccif CDCN
	// *
	// * @param 微信号
	// * @return CDCN
	// */
	// public String queryCDCNByWechatAccount(String wechatAccount) {
	// LOGGER.debug("enter queryCDCNByWechatAccount() param:" + wechatAccount);
	// return cdcn;
	// }

	// /**
	// * 获取Ccif CDCN
	// *
	// * @param ccif号
	// * @return CDCN
	// */
	// public String queryCDCNByCcifNo(String ccifNo) {
	// LOGGER.debug("enter queryCDCNByCcifNo() param:" + ccifNo);
	// return cdcn;
	// }

	/**
	 * 获取Ccif CDCN
	 * 
	 * @param orgNo
	 *            组织机构号
	 * @return CDCN
	 */
	public Map<String, String> queryCDCNByOrgNo(String[] orgNo) {
		LOGGER.debug("enter queryCDCNByOrgNo() param:" + orgNo);
		return getCcifDcnMap(orgNo);
	}

	/**
	 * 获取Ccif CDCN
	 * 
	 * @param bizPermNo
	 *            营业执照号
	 * @return CDCN
	 */
	public Map<String, String> queryCDCNByBizPermNo(String[] bizPermNo) {
		LOGGER.debug("enter queryCDCNByBizPermNo() param:" + bizPermNo);
		return getCcifDcnMap(bizPermNo);
	}

	/**
	 * 获取Ccif CDCN
	 * 
	 * @param finLicNo
	 *            金融许可证号
	 * @return CDCN
	 */
	public Map<String, String> queryCDCNByFinLicNo(String[] finLicNo) {
		LOGGER.debug("enter queryCDCNByFinLicNo() param:" + finLicNo);
		return getCcifDcnMap(finLicNo);
	}

	/**
	 * 获取Ccif CDCN
	 * 
	 * @param entCode
	 *            企业代码证号
	 * @return CDCN号
	 */
	public Map<String, String> queryCDCNByEntCode(String[] entCode) {
		LOGGER.debug("enter queryCDCNByEntCode() param:" + entCode);
		return getCcifDcnMap(entCode);
	}

	/**
	 * 获取Ccif CDCN
	 * 
	 * @param swiftCode
	 *            swift代码
	 * @return CDCN号
	 */
	public Map<String, String> queryCDCNBySwiftCode(String[] swiftCode) {
		LOGGER.debug("enter queryCDCNBySwiftCode() param:" + swiftCode);
		return getCcifDcnMap(swiftCode);
	}

	/**
	 * 获取Ccif CDCN
	 * 
	 * @param clientNo
	 *            兴业客户号
	 * @return CDCN号
	 */
	public Map<String, String> queryCDCNByXYClientNo(String[] clientNo) {
		LOGGER.debug("enter queryCDCNByXYClientNo() param:" + clientNo);
		return getCcifDcnMap(clientNo);
	}

	/**
	 * 获取Ccif CDCN
	 * 
	 * @param qqNo
	 *            qq号
	 * @return CDCN号
	 */
	public Map<String, String> queryCDCNByQQNo(String[] qqNo) {
		LOGGER.debug("enter queryCDCNByQQNo() param:" + qqNo);
		return getCcifDcnMap(qqNo);
	}

	/**
	 * 获取Ccif CDCN
	 * 
	 * @param wechatAccount
	 *            微信号
	 * @return CDCN号
	 */
	public Map<String, String> queryCDCNByWechatAccount(String[] wechatAccount) {
		LOGGER.debug("enter queryCDCNByWechatAccount() param:" + wechatAccount);
		return getCcifDcnMap(wechatAccount);
	}

	/**
	 * 获取Ccif CDCN
	 * 
	 * @param ccifNo
	 *            ccif号
	 * @return 包含Ccif CDCN的map
	 */
	public Map<String, String> queryCDCNByCcifNo(String[] ccifNo) {
		LOGGER.debug("enter queryCDCNByCcifNo() param:" + ccifNo);
		return getCcifDcnMap(ccifNo);
	}

	private Map<String, String> getCcifDcnMap(String[] key) {
		if (key == null || key.length <= 0) {
			LOGGER.error("param null or length <= 0");
			return null;
		}
		Map<String, String> map = new HashMap<String, String>();
		for (String k : key) {
			if (k == null || "".equals(k)) {
				LOGGER.error("param null");
				return null;
			}
			map.put(k, this.getCcifDcn());
		}
		return map;
	}

	/**
	 * 根据QQ号/微信账号/银行卡号/银行账号查询
	 */
	private byte[] queryInput(List<String> queryDatas, String flag)
			throws GNSException {
		if (queryDatas != null && queryDatas.size() > 0) {
			BatchQueryDcnReq.Builder builder = BatchQueryDcnReq
					.newBuilder();
			QueryInput.Builder queryBuilder = QueryInput
					.newBuilder();
			for (int i = 0; i < queryDatas.size(); i++) {
				String value = queryDatas.get(i);
				Integer val = GNS_INPUT_TYPE.getValByKey(flag);
				queryBuilder.setInputType(val);
				ByteString byteString = ByteString.copyFrom(value.getBytes());
				queryBuilder.setInput(byteString);
				QueryInput input = queryBuilder.build();
				builder.addInputList(input);
				queryBuilder.clear();
			}
			BatchQueryDcnReq batchQueryDcnReq = builder.build();
			byte[] byteArray = batchQueryDcnReq.toByteArray();
			int subcmd = GnsMsg.SUBCMD_FOR_GNS.SUBCMD_BATCH_QUERY_VALUE;
			byte byteVal = Integer.valueOf(subcmd).byteValue();
			byte[] resultBytes = mergeBytes(byteVal, byteArray);
			return resultBytes;
		}
		return null;
	}

	private byte[] mergeBytes(Byte byteValue, byte[] bytes) {
		byte[] resultBytes = new byte[bytes.length + 1];
		resultBytes[0] = byteValue;
		for (int i = 1; i < resultBytes.length; i++) {
			resultBytes[i] = bytes[i - 1];
		}
		return resultBytes;
	}

	// private AddBindInfo.Builder createUserBindInfoBuilder(int inputType,
	// String bindData, String ecifNumber) {
	// AddBindInfo.Builder userBindInfoBuilder = AddBindInfo.newBuilder();
	// userBindInfoBuilder.setBindType(inputType);
	// userBindInfoBuilder.setEcifNum(ByteString.copyFrom(ecifNumber
	// .getBytes()));
	// userBindInfoBuilder
	// .setBindData(ByteString.copyFrom(bindData.getBytes()));
	// return userBindInfoBuilder;
	// }

	private Map<String, String> getResponseDcnList(Response response)
			throws InvalidProtocolBufferException {
		if (checkReponse(response)) {
			String content = response.getMessage().getContent();
			content = content.substring(1, content.length());
			// byte[] bytes = content.getBytes();

			// System.out.println(bytes.length);

			BatchQueryDcnRsp batchQueryDcnRsp = BatchQueryDcnRsp
					.parseFrom(content.getBytes());

			List<QueryOutput> outputList = batchQueryDcnRsp.getOutputListList();
			if (outputList != null && !outputList.isEmpty()) {
				Iterator<QueryOutput> iterator = outputList.iterator();
				HashMap<String, String> resultMap = new HashMap<String, String>();
				while (iterator.hasNext()) {
					QueryOutput output = iterator.next();
					String dcnNumber = output.getDcnNum().toStringUtf8();
					String key = output.getInput().toStringUtf8();
					if ("".equals(dcnNumber)) {
						resultMap.put(key, null);
					} else {
						resultMap.put(key, dcnNumber);
					}
				}
				return resultMap;
			}
		}
		return null;
	}

	private String getReponseDcn(Response response)
			throws InvalidProtocolBufferException {
		Map<String, String> resultMap = getResponseDcnList(response);
		if (resultMap != null && !resultMap.isEmpty()) {
			return new ArrayList<String>(resultMap.values()).get(0);
		}
		return null;
	}

	// private DeleteUserInfo.Builder createBatchDeleteInfoReq(int type,
	// String value) {
	// DeleteUserInfo.Builder builder = DeleteUserInfo.newBuilder();
	// builder.setDeleteType(type);
	// builder.setDeleteData(ByteString.copyFrom(value.getBytes()));
	// return builder;
	// }

	private boolean checkReponse(Response response) {
		if (response != null && response.getMessage() != null
				&& hashText(response.getMessage().getContent())) {
			return true;
		}
		return false;
	}

	private boolean hashText(String text) {
		if (text != null && !"".equals(text)) {
			return true;
		}
		return false;
	}

}